<script setup lang="ts">
defineOptions({
  // name 作为一种规范最好必须写上并且和路由的name保持一致
  name: "Users"
});
import { getUserList, addUser, editUser, deleteUser, editPassword } from "@/api/user";
import { message } from "@/utils/message";
import { reactive, ref, onMounted, toRefs } from "vue";
import { mainUrl } from "@/api/utils";
import { avatar } from "../login/utils/static";
import { editAvatar } from "@/api/server";
const state = reactive({
  circleUrl:
    'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
  squareUrl:
    'https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png',
  sizeList: ['small', '', 'large'] as const,
})

const { circleUrl, squareUrl, sizeList } = toRefs(state);
const showTip = ref(false);

onMounted(async () => {
  //获取用户列表
  getList(userPage)
});
const getList = async (data) => {
  let res = await getUserList(data);
  console.log('用户列表', res)
  total.value = res.data.count;
  tableData.value = res.data.data;
};
const userPage = reactive({
  page: 1,
  count: 10,
  key: ""
});
const total = ref(10);
interface User {
  user_id: string;
  username: string;
  password: string;
  phone: string;
  email: string;
  balance: number;
  reg_time: string;
}

//判断新增还是编辑用户信息变量
const addOrEdit = ref(false);

const tableData = ref([]);
const dialogOverflowVisible = ref(false);

const form = reactive({
  user_id: "",
  username: "",
  password: "",
  phone: "",
  email: "",
  balance: 0,
  reg_time: "",
  avatar: '',
  user_type: null,
  name: '',
  card_id: '',
  real_name_state: null

});
//修改用户密码
const passwordVisible = ref(false);
const submitPassword = async () => {
  let res = await editPassword({ user_id: form.user_id, password: form.password });
  console.log('修改密码', res);
  if (res.data.code == 200) {
    message("修改成功！", { type: "success" });
    passwordVisible.value = false;
  }
}
//搜索
const findIt = async () => {
  getList(userPage)
};

function show_table(data = null) {
  if (data == null) {
    Object.keys(form).forEach(key => {
      form[key] = null;
    });
  } else {
    Object.keys(data.row).forEach(key => {
      form[key] = data.row[key];
    });
  }
}
//分页
const handleCurrentPageChange = async newPage => {
  userPage.page = newPage;
  getList(userPage)

};
const handlePageSizeChange = async newSize => {
  userPage.count = newSize;
  getList(userPage)

};
// 删除用户
const handleDelete = async (index: number, row: User) => {
  let res = await deleteUser({ user_id: row.user_id });
  if (res.data.code == 200) {
    message("删除成功！", { type: "success" });
    //更新数据
    getList(userPage)
  }
};
// 提交数据
const onSubmit = async () => {
  if (addOrEdit.value) {
    let res = await addUser(form);
    console.log("新增用户", res.data);
    if (res.data.code == 200) {
      message("添加成功！", { type: "success" });
      dialogOverflowVisible.value = false;
    } else {
      message(res.data.data, { type: "error" });
    }
  } else {
    console.log("编辑用户");
    let res = await editUser(form);
    if (res.data.code == 200) {
      message("修改成功！", { type: "success" });
      dialogOverflowVisible.value = false;
    }
  }
  //更新数据
  getList(userPage)
};
//头像
const onFileSelected = (event) => {
  const file = event.target.files[0];
  if (file) {
    editAvatar({ file: file, user_id: form.user_id }).then((res) => {
      console.log('上传文件', res)
      if (res.data.code == 200) {
        message('上传成功', { type: 'success' });
        console.log('新头像', res.data.data.avatar);
        form.avatar = res.data.data.avatar;

      } else {
        message(res.data.msg, { type: 'error' });
      }
    })
  }
}
const handleMouseEnter = () => {
  showTip.value = true;
};
const handleMouseLeave = () => {
  showTip.value = false;
}
</script>

<template>
  <div class="body">
    <div class="table_box">
      <el-table class="table_el" :data="tableData" style="width: auto">
        <el-table-column label="ID" prop="user_id" width="60" />
        <el-table-column label="用户名" prop="username" />
        <el-table-column label='头像'>
          <template #default="scope"><img v-if="scope.row.avatar"
              :src='`${mainUrl}/v1/attachment/get_attachment?aid=${scope.row.avatar}`'
              style="width: 40px;height: 40px;border-radius:50%" /></img>
            <span v-else>暂无头像</span>
          </template>
        </el-table-column>
        <el-table-column label='权限'>
          <template #default="scope">{{ scope.row.user_type == 1 ? '管理员' : '普通用户' }}</template>
        </el-table-column>
        <el-table-column label="手机" prop="phone" />
        <el-table-column label="邮箱" prop="email" />
        <el-table-column label="余额" prop="balance" />
        <el-table-column label="注册时间" prop="reg_time" width="120" />
        <el-table-column label="实名状态">
          <template #default="scope">
            <el-tag v-if="scope.row.real_name_state == 1" type="success">已实名</el-tag>
            <el-tag v-if="scope.row.real_name_state == 0" type="info">未实名</el-tag>
            <el-tag v-if="scope.row.real_name_state == 2" type="info">审核中</el-tag>
            <el-tag v-if="scope.row.real_name_state == 3" type="info">未通过</el-tag>

          </template>
        </el-table-column>
        <el-table-column width="200">
          <template #header>
            <el-input v-model="userPage.key" size="small" placeholder="关键字筛选" @blur="findIt" />
          </template>
          <template #default="scope">
            <el-button size="small"><router-link
                :to="'/users/info?user_id=' + scope.row.user_id">管理</router-link></el-button>
            <el-button size="small" @click="
              show_table(scope);
            dialogOverflowVisible = true;
            addOrEdit = false;
            ">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="table_pagination">
        <el-button type="primary" @click="
          show_table();
        dialogOverflowVisible = true;
        addOrEdit = true;
        ">
          添加用户
        </el-button>
        <el-pagination background layout="prev, pager, next,sizes" :total="total" :current-page="userPage.page"
          :page-size="userPage.count" :page-sizes="[10, 20, 50, 100]" @update:current-page="handleCurrentPageChange"
          @update:page-size="handlePageSizeChange" />

      </div>
    </div>

    <el-dialog v-model="dialogOverflowVisible" title="用户信息" width="500" draggable overflow>
      <div>
        <el-form :model="form" label-width="auto" style="max-width: 600px">
          <el-form-item label="用户名" required>
            <el-input v-model="form.username" placeholder="请输入用户名" required />
          </el-form-item>
          <el-form-item v-if="!addOrEdit" label="头像">
            <div class="block" @mouseenter="handleMouseEnter" @mouseleave="handleMouseLeave">
              <el-avatar :size="50"
                :src="form.avatar ? `${mainUrl}/v1/attachment/get_attachment?aid=${form.avatar}` : circleUrl"
                class="avatar-hover" @click="$refs.fileInput.click()" />
              <div v-if="showTip" class="change-avatar-tip">点击修改头像</div>
              <input ref="fileInput" type="file" style="display:none" @change="onFileSelected" />
            </div>

          </el-form-item>
          <el-form-item label="权限" required>
            <el-select v-model="form.user_type" placeholder="请选择用户权限">
              <el-option label="管理员" :value=1 />
              <el-option label="普通用户" :value=0 />
            </el-select>
          </el-form-item>
          <el-form-item label="密码" required>
            <el-input v-if="addOrEdit" v-model="form.password" placeholder="请输入密码" required />
            <el-button v-if="!addOrEdit" type="danger" plain
              @click="passwordVisible = true; form.password = ''">修改密码</el-button>
          </el-form-item>
          <el-form-item label="手机号">
            <el-input v-model="form.phone" placeholder="请输入手机号" />
          </el-form-item>
          <el-form-item label="邮箱">
            <el-input v-model="form.email" placeholder="请输入邮箱" />
          </el-form-item>
          <el-form-item label="姓名">
            <el-input v-model="form.name" placeholder="请输入姓名" />
          </el-form-item>
          <el-form-item label="身份证">
            <el-input v-model="form.card_id" placeholder="请输入身份证" />
          </el-form-item>
          <el-form-item label="实名状态">
            <el-select v-model="form.real_name_state" placeholder="请选择用户实名状态">
              <el-option label="已实名" :value=1 />
              <el-option label="未实名" :value=0 />
              <el-option label="审核中" :value=2 />
              <el-option label="未通过" :value=3 /></el-select>
          </el-form-item>

        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogOverflowVisible = false">关闭</el-button>
          <el-button type="primary" @click="onSubmit"> 提交 </el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="passwordVisible" title="修改密码" width="500" draggable overflow>
      <div>
        <el-form :model="form" label-width="auto" style="max-width: 600px">
          <el-form-item label="密码" required>
            <el-input v-model="form.password" placeholder="请输入密码" required />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="passwordVisible = false">关闭</el-button>
          <el-button type="primary" @click="submitPassword"> 提交 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style>
.table_box {
  display: flex;
  flex-direction: column;
  height: 50%;
}

.table_box .table_el {
  flex: 1;
}

.table_pagination {
  background-color: #fff;
  padding: 8px 30px;
  display: flex;
  justify-content: space-between;
}
</style>
